package com.arox.springinaction.post;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageConsumer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service("backOfficeJms")
public class BackOfficeJmsImpl implements BackOffice {
    
    @Value("${jms.brokerURL}")
    private String brokerURL;
    
    @Value("${jms.mail.queue}")
    private String queueName;

    public Mail receiveMail() {
	ConnectionFactory cf = new ActiveMQConnectionFactory(brokerURL);
	Destination destination = new ActiveMQQueue(queueName);
	Connection conn = null;
	try {
	    conn = cf.createConnection();
	    Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
	    MessageConsumer consumer = session.createConsumer(destination);
	    conn.start();
	    MapMessage message = (MapMessage) consumer.receive(1000);
	    session.close();
	    if (message == null) {
		return null;
	    }
	    Mail mail = new Mail();
	    mail.setMailId(message.getString("mailId"));
	    mail.setCountry(message.getString("country"));
	    mail.setWeight(message.getDouble("weight"));
	    return mail;
	} catch (JMSException e) {
	    throw new RuntimeException(e);
	} finally {
	    if (conn != null) {
		try {
		    conn.close();
		} catch (JMSException e) {
		}
	    }
	}
    }

}
